<template>
  <div class="common-layout">
    <el-container>


      <el-container>

        <!-- 侧边栏部分 -->
        <el-aside :width="isCollapse ? '68px' : '220px'" class="app-aside">
          <h3>MyTime</h3>


          <!-- 菜单 -->
          <el-menu :collapse="isCollapse" class="el-menu-vertical-demo" :default-active="activeMenu" router
            @select="handleMenuSelect">
            <el-sub-menu  v-if="hasSystemManagement" index="system-management">
              <template #title>
                <el-icon>
                  <Location />
                </el-icon>
                <span class="fonts"> 系统管理</span>
              </template>
              <el-menu-item v-for="item in systemManagementMenus" :key="item.index" :index="item.index">
                <span class="subfonts">{{ item.title }}</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu  v-if="hasSystemMonitor"  index="system-monitor">
              <template #title>
                <el-icon>
                  <Operation />
                </el-icon>
                <span class="fonts">系统监控</span>
              </template>
              <el-menu-item v-for="item in systemMonitorMenus" :key="item.index" :index="item.index" class="subfonts">
                <span class="subfonts">{{ item.title }}</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 其他菜单项 -->
            <el-menu-item v-for="item in otherMenus" :key="item.index" :index="item.index">
              <el-icon>
                <component :is="item.icon" />
              </el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主体内容部分 -->
        <el-container class="el-right">
          <!-- 页头部分 -->
          <el-header class="app-header">
            <div class="header-content">
              <div @click="toggleCollapse" style="margin-top: 3px;">
                <el-icon v-if="isCollapse"  style="font-size: 28px;">
                  <Expand ></Expand>
                </el-icon>
                <el-icon v-else style="font-size: 28px;">
                  <Fold />
                </el-icon>
              </div>
              <el-dropdown placement="bottom-end" @command="handleCommand">

                <el-avatar :src="avatar" class="el-dropdown__box" />

                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
                    <el-dropdown-item command="update" :icon="Crop">修改信息</el-dropdown-item>
                    <el-dropdown-item command="rePassword" :icon="EditPen">重置密码</el-dropdown-item>
                    <el-dropdown-item command="logout" :icon="SwitchButton" @click="handleLogout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-header>
          <el-main class="main-container">
            <el-tabs v-model="editableTabsValue" type="card" editable class="demo-tabs" @edit="handleTabsEdit"
              @tab-click="handeTabsClick">
              <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
               
                  <router-view :key="item.name" />
                
                
              </el-tab-pane>
            </el-tabs>

          </el-main>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch,computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ElContainer, ElAside, ElHeader, ElMain, ElMenu, ElMenuItem, ElSubMenu, ElIcon, ElTabs, ElTabPane, ElDropdown,
  ElDropdownMenu, ElDropdownItem, ElAvatar, ElMessageBox, ElMessage
} from 'element-plus';
import {DArrowLeft, DArrowRight, Location, Setting, User, Crop, EditPen, SwitchButton, Operation} from '@element-plus/icons-vue';
import avatar from '../assets/avater.jpg'; // 确保路径正确
import type { TabPaneName, TabsPaneContext } from 'element-plus'
import { useTokenStore } from "../stores/token.ts";
import { useUserStore } from "../stores/UserStore";
import { Userlogout } from '../api/userApi.ts';
const tokenStore=useTokenStore()
const userStore=useUserStore()
// 定义类型
interface Tab {
  title: string;//标签标题
  name: string;//路由名称
}
interface MenuItem {
  index: string;
  title: string;
  icon: string;
  roles: string[]; // 允许访问的角色列表
}
const isCollapse = ref(false); // 控制侧边栏的展开/收起
const activeMenu = ref<string>(''); // 当前选中的菜单项
const editableTabsValue = ref<string>(''); // 当前选中的 tab 路由
const editableTabs = reactive<Tab[]>([]); // 动态生成的 tabs
const router = useRouter();
const route = useRoute();


// 切换侧边栏的展开/收起
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};


// 导航菜单列表（可以进一步优化为动态加载）添加 roles 属性
const menuList: MenuItem[] = [
  { index: '/home/user', title: '用户管理', icon: 'User', roles: ['ROLE_admin'] },
  { index: '/home/logs', title: '系统日志', icon: 'Operation', roles: ['ROLE_admin', 'ROLE_user'] },
  { index: '/home/docs', title: '文档说明', icon: 'Setting', roles: ['ROLE_admin', 'ROLE_user'] },
  { index: '/home/myfile', title: '文件管理', icon: 'Crop', roles: ['ROLE_admin', 'ROLE_user'] },
];
// 计算过滤后的菜单列表
const filteredMenuList = computed(() => {
   const list=menuList.filter(menu => {
    // 如果菜单项没有 roles 属性，则默认所有角色可见
    if (!menu.roles || menu.roles.length === 0) {
      return true;
    }
    // 检查用户是否具有访问该菜单的角色
    const premissions = userStore.userInfo.authorityStrings || [];
    return menu.roles.some(role => premissions.indexOf(role) >= 0);
  });
  return list;
});
// 分组菜单项
const systemManagementMenus = computed(() => {
  return filteredMenuList.value.filter(menu => menu.index.startsWith('/home/user') || menu.index.startsWith('/home/myfile'));
});

const systemMonitorMenus = computed(() => {
  return filteredMenuList.value.filter(menu => menu.index.startsWith('/home/logs'));
});

const otherMenus = computed(() => {
  return filteredMenuList.value.filter(menu => menu.index.startsWith('/home/docs'));
});
// 判断用户是否有访问某个子菜单组的权限
const hasSystemManagement = computed(() => {
  return systemManagementMenus.value.length > 0;
});

const hasSystemMonitor = computed(() => {
  return systemMonitorMenus.value.length > 0;
});
// 处理菜单选择事件
const handleMenuSelect = (index: string) => {
  if (!index) return;
  // 检查是否已经有这个 tab，如果没有则添加
  const existingTab = editableTabs.find((tab) => tab.name === index);
  if (!existingTab) {
    const newTab: Tab = {
      title: getTabTitle(index),
      name: index,
    };
    editableTabs.push(newTab);
  }
  editableTabsValue.value = index; // 切换到新添加的 tab
  router.push(index); // 直接导航到对应路由
};

// 根据菜单项的 index 获取对应的标题
const getTabTitle = (index: string): string => {
  const found = menuList.find((menu) => menu.index === index);
  return found ? found.title : '新标签页';
};
// 导航到对应的路由
const navigateToRoute = (index: string) => {
  router.push(index);
};
// 处理标签页编辑（关闭）
const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: 'remove' | 'add'
) => {
  if (action === 'remove') {
    const tabIndex = editableTabs.findIndex((tab) => tab.name === targetName);
    if (tabIndex !== -1) {
      editableTabs.splice(tabIndex, 1);
      if (editableTabs.length) {
        editableTabsValue.value = editableTabs[0].name;
        navigateToRoute(editableTabs[0].name);
      } else {
        editableTabsValue.value = '';
        router.push('/home'); // 默认路由
      }
    }
  }
  // 如果需要处理 'add' 动作，可以在这里添加逻辑

};
//处理标签页点击
const handeTabsClick = (pane: TabsPaneContext, ev: Event) => {
  editableTabsValue.value = pane.paneName?.toString() || '';
  activeMenu.value = pane.paneName?.toString() || '';
  navigateToRoute(pane.paneName?.toString() || '');
};

// 监听路由变化，自动选中对应的 tab
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/home') {
      editableTabsValue.value = '';
      activeMenu.value = '';
      return;
    }
    const existingTab = editableTabs.find((tab) => tab.name === newPath);
    if (existingTab) {
      editableTabsValue.value = existingTab.name;
      activeMenu.value = newPath;
    } else {
      handleMenuSelect(newPath);
      activeMenu.value = newPath;
    }
  },
  { immediate: true }
);

// 定义一个枚举来管理命令类型，以增强代码的可读性和易维护性
enum Command {
  PersonInfo = 'personInfo',
  Logout = 'logout',
  UpdateInfo = 'updateInfo',
  UpdatePwd = 'updatePwd'
}
const handleCommand = async (command: Command) => {
  switch (command) {
    case Command.PersonInfo:
      //await handlePersonInfo();
      break;
    case Command.Logout:
      //await handleLogout();
      break;
    case Command.UpdateInfo:
      //await handleUpdateInfo();
      break;
    case Command.UpdatePwd:
      //await handleUpdatePwd();
      break;

  }
};
// 处理用户退出登录的逻辑
async function handleLogout() {
  try {
    const confirmation = await ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // 用户确认退出
    const response = await Userlogout();
    
      tokenStore.removeToken();      // 清空token
      //userInfoStore.removeInfo();    // 清空用户信息
      ElMessage.success('退出登录成功');
      router.push('/login');              // 跳转到登录页面
    
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已撤销该操作'
      });
    } else {
      console.error('Error during logout:', error);
      ElMessage.error('退出登录失败');
    }
  }
}
</script>
<style lang="scss" scoped>
/* 全局 box-sizing */
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* 使根布局占满整个视口高度和宽度 */
.common-layout {
  height: 100vh;
  /* 视口高度 */
  width: 100vw;
  /* 视口宽度 */
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

/* 使 el-container 在根布局中占满剩余空间 */
.el-container {
  flex: 1;
  height: 100%;
  width: 100%;
  background-color: #f0f0ff;
}
.el-right{
 
  .main-container{
    padding: 10px;
  .el-tabs{
    padding: 10px;
    background-color: #ffffff;
    border-radius: 15px;
   
  }
}

}



/* 标签页内容的样式 */
.demo-tabs>.el-tabs__content {
  padding: 24px;
  color: #606266;
  font-size: 16px;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  border-top: none;
}

/* 页头样式 */
.app-header {
  background-color: #9c8fdfee;
  color: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    width: 100%;

    h1 {
      margin: 0;
      font-size: 24px;
    }

    .el-dropdown__box {
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #f5f7f8;


      }

      .el-avatar {
        margin-left: 2px;
      }
    }
  }
}

// 悬浮效果
.el-avatar {
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.1);
  }
}

.el-dropdown-menu {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 10px 0;

  .el-dropdown-item {
    padding: 10px 20px;
    color: #333;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: background-color 0.3s ease, color 0.3s ease;

    &:hover {
      background-color: #409eff;
      color: #fff;
      cursor: pointer; //设置鼠标样式
    }

    &.is-active {
      background-color: #409eff;
      color: #fff;
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}

/* Sidebar.scss */

$primary-color: #e2e0fd;
$hover-color: #fae5e5;
$active-color: #dbcffb;
$menu-font-color: #434343;
$menu-icon-color: #434343;
.app-aside {
  background-color: $primary-color;/* 紫色，85% 透明度 */
  color: #434343; /* 白色文字 */
  transition: width 0.3s ease;

  h3 {
    color: #434343;
    text-align: center;
    padding: 20px 0;
    font-size: 1.5em;
    margin: 0;
  }

  .el-menu-vertical-demo {
    background-color:$primary-color; /* 继承父元素的背景色 */
    border-right: none;

    .el-menu-item ,.el-sub-menu{
      color: $menu-font-color;
      background-color:$primary-color;
      transition: background-color 0.3s ease, color 0.3s ease;

    }

    .el-menu-item.is-active,
    .el-sub-menu.is-active > .el-sub-menu__title {
      background-color: $active-color; /* 选中项稍微亮一点 */
      color: $menu-font-color;
    }

    .el-sub-menu__title {
      display: flex;

      .el-icon {
        margin-right: 15px;
        color: $menu-icon-color;
      }
      .fonts{
        color: $menu-font-color;
      }
     
    }

    .el-menu-item {
      display: flex;
     
      .el-icon {
        margin-right: 15px;
        color: $menu-icon-color;
      }
      .subfonts{
        margin-left: 35px;
      }
      
    }
  }

  /* 处理折叠状态 */
  &[class*="is-collapse"] {
    background-color: $primary-color; /* 保持相同的背景色 */

    .el-menu-vertical-demo {
      .el-menu-item,
      .el-sub-menu__title {
        text-align: center;

        .el-icon {
          margin-right: 0;
          font-size: 1.5em;
        }

        span {
          display: none; /* 隐藏文字，仅显示图标 */
        }
      }

      .el-menu-item.is-active,
      .el-sub-menu.is-active > .el-sub-menu__title {
        background-color: rgba(255, 255, 255, 0.2); /* 保持选中项颜色 */
      }
    }

    h3 {
      font-size: 1.2em;
    }
  }
}


/* 响应式调整 */
@media (max-width: 768px) {
  .app-header {
    flex-direction: column;
    align-items: flex-start;

    .header-content {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  .app-aside {
    width: 100%;
    height: auto;
  }

  .button-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
